<?php

namespace App\Http\Controllers;

use App\Events\OrderShipped;
use App\Http\Controllers\Admin\Business\Repository\Combo;
use App\Http\Controllers\Admin\Business\Repository\ComboOrder;

use App\Http\Controllers\Admin\Member\Repository\Member;
use App\Notifications\InvoicePaid;
use App\PayOrder;
use App\PrizeSetting;
use App\Repositories\DistributeRepository;
use App\Repositories\OrderRepository;
use App\Repositories\UserRepository;
use App\Setting;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;

use EasyWeChat\Payment\Order;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;


class PaymentController extends Controller
{

    public function order()
    {
        $app = app('wechat');
        $payment = $app->payment;
        $attributes = [
            'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
            'body' => 'iPad mini 16G 白色',
            'detail' => 'iPad mini 16G 白色',
            'out_trade_no' => '121772521227033233868075',
            'total_fee' => 1, // 单位：分
            'notify_url' => env('APP_URL') . '/payment', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid' => 'oA00lwIQMP42BLxIwOi5A5BJM7Do', // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
        ];
        //  dd($attributes);
        $order = new Order($attributes);
        $result = $payment->prepare($order);
        //dd($result);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            //      $config = $payment->configForJSSDKPayment($prepayId); // 返回数组

            $js = $app->js;

            return view('web.payment.payment', compact('json', 'js'));

        }
    }

    public function jspayfor()
    {
        $app = app('wechat');
        $js = $app->js;
        return view('web.payment.payment', compact('js'));
    }

    public function payFor(Request $request)
    {

        $app = app('wechat');
        $payment = $app->payment;
        if($request->total_num<1){

            return [
                'info' => 'error',
                'msg' => '订单数量不能小于1',
            ];
        }
        $attributes = $this->getOrder($request, $request->type);

        $order = new Order($attributes);
        $result = $payment->prepare($order);

       // return $result;
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            $json = json_decode($json, true);
            //      $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
            return [
                'info' => 'success',
                'msg' => $json,
                'out_trade_no'=>$attributes['out_trade_no']
            ];
        } else {
            return [
                'info' => 'error',
                'msg' => $result,
            ];
        }
    }

    /**
     * @param $type 1 老虎机 2 套餐
     */
    protected function getOrder(Request $request, $type)
    {
        $order = new OrderRepository();
        if ($type == 1) {//老虎机游戏
            $gamePrice = Setting::getConfig('game', '网站设置');

            $arrtibutes = [
                'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
                'body' => '老虎机游戏',
                'detail' => '老虎机游戏',
                'out_trade_no' => $order->outTradeNo(),
                'total_fee' => (int)round($gamePrice*100), // 单位：分
                'notify_url' => config('app.url') . '/payment', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'openid' => Auth::guard('member')->user()->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                'attach' => 'game'
            ];
        } elseif ($type == 2) {//套餐
            $total_num=$request->total_num ?? 1;
            $arrtibutes = $order->addOrder($request->combo_id,$total_num);
        }
        PayOrder::create($arrtibutes);
        return $arrtibutes;
    }

    public function payment(Request $request)
    {

        Log::info('支付成功');

        $app = app('wechat');
        $response = $app->payment->handleNotify(function ($notify, $successful) {
            // 你的逻辑
            $payOrder = PayOrder::where('out_trade_no', $notify['out_trade_no'])->first();

          //  Log::info('notify',$notify);
            if ($payOrder) {
                if ($payOrder->is_pay == 1) {
                    return true;
                }
                Log::info('支付3');
                $payOrder->is_pay = 1;
                $payOrder->save();
                if ($payOrder->attach == 'game') {
                    Log::info('街道支付4');
                    $member = Member::where('openid', $notify['openid'])->firstOrfail();
                    //增加一次
                    $member->increment('game_num',1);
                } elseif ($payOrder->attach == 'combo') {
                    Log::info('支付5');
                    $distribute = new DistributeRepository();
                    $order = ComboOrder::where('outTradeNo', $notify['out_trade_no'])->firstOrFail();
                    //增加次数
                    $member = Member::where('id', $order->member_id)->firstOrfail();
                    $true = $member->increment('wallet_spots', $order->times);
                    //抽奖
                  //  $prize= new PrizeSetting();
                   // $prize->handlePrize($member->id,$payOrder);
                    //分销
                    $distribute->account($order->member_id, DistributeRepository::ACT_COMBO_BUY, ['order_id' => $order->id]);
                    Log::info('支付6');
                    $combo= Combo::find($order->combo_id);
                    if($combo->is_bind==1){
                     //   $member->notify(new InvoicePaid('华山旅游提示:门票序列号为'.$order->outTradeNo.'请前往兑换'));
                    }
                    event(new OrderShipped($order));
                }
                return true;
            }
        }
        );
        return $response; // Laravel 里请使用：return $response;
    }
}
